// Blowfish symmetric encryption test

#include <QApplication>
#include <QFile>
#include <QDataStream>
#include <QDebug>

#include "gencryptor.h"
#include "gexception.h"


int main( int argc, char** argv )
{
	QCoreApplication app( argc, argv );
	
	if ( argc < 3 )
	{
		qDebug() << "Usage: testblowfish <keyfile> <datafile>";
		return 1;
	}
	
	try{
	
	qDebug() << "Initializing encryptor and decryptor";
	GEncryptor encryptor;
	GEncryptor decryptor;
	
	// load key
	qDebug() << "Loading encryptor key from file  " << argv[1];
	encryptor.setKeyFromFile( argv[1] );
	
	qDebug() << "Loading decryptor key from file  " << argv[1];
	decryptor.setKeyFromFile( argv[1] );
	
	// load data file 
	qDebug() << "Loading data file";
	QFile file( argv[2] );
	if ( ! file.open( QFile::ReadOnly ) )
	{
		qDebug() << "can not load data file " << argv[2] << ":" << file.errorString();
		return 1;
	}
	QByteArray data = file.readAll();
	qDebug() << "readed data: " << data.size() << " bytes";
	
	// encode
	qDebug() << "Encoding";
	QByteArray encoded = encryptor.encrypt( data );
	qDebug() << "Encoded data: " << encoded.size() << "bytes";
	
	if ( encoded.size() < data.size()  ||  encoded.size()  > data.size() + 11 )
	{
		qDebug("Encoded data size invalid: %d vs %d", encoded.size(), data.size() );
		return 1;
	}
	
	// decode
	qDebug() << "Decoding";
	QByteArray decoded = decryptor.decrypt( encoded );
	qDebug() << "Decoded data: " << decoded.size() << "bytes";
	
	if ( decoded.size() != data.size() )
	{
		qDebug("Decoded data size invalid: %d vs %d", decoded.size(), encoded.size() );
		return 1;
	}
	
	// compare data
	qDebug() << "Comparing data";
	for ( int i = 0; i < data.size(); i++ )
	{
		if ( data[i] != decoded[i] )
		{
			qDebug( "Error on byte %d (%d vs %d)", i, (int)data[i], (int)decoded[i] );
			return 1;
		}
		
	}
	
	
	qDebug(" TEST PASSED");
	// catch exceptions
	} catch( GException& e )
	{
		qDebug() << "Exeption thrown: " << e.getMessage();
	}
	catch ( ... )
	{
		qDebug("Unknown exception");
	}
	
}

